"""
学生选课模型
"""
from datetime import datetime
from app.extensions import db


class StudentCourse(db.Model):
    """学生选课关联表"""
    __tablename__ = 'student_courses'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    student_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id'), nullable=False, index=True)
    enrollment_date = db.Column(db.Date, nullable=False, index=True)
    academic_year = db.Column(db.String(20), index=True, comment='学年')
    semester_term = db.Column(db.String(20), index=True, comment='学期')
    exam_type = db.Column(db.String(50), index=True, comment='课程性质(正常考试/补考/缓考等)')
    credit_type = db.Column(db.String(50), comment='学分类型(主修/辅修等)')
    gpa = db.Column(db.Numeric(3, 2), comment='绩点')
    class_number = db.Column(db.String(50), comment='教学班号')
    status = db.Column(db.Enum('enrolled', 'completed', 'dropped'), default='enrolled')
    score = db.Column(db.Numeric(5, 2))
    letter_grade = db.Column(db.String(2))
    midterm_score = db.Column(db.Numeric(5, 2), comment='平时成绩')
    final_score = db.Column(db.Numeric(5, 2), comment='考试成绩')
    graded_at = db.Column(db.DateTime)
    total_classes = db.Column(db.Integer)
    attended = db.Column(db.Integer)
    attendance_rate = db.Column(db.Numeric(5, 2))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    student = db.relationship('User', foreign_keys=[student_id], backref='student_courses_enrolled')
    course = db.relationship('Course', back_populates='student_courses')
    assignments = db.relationship('AssignmentScore', backref='student_course', cascade='all, delete-orphan')
    
    __table_args__ = (
        db.UniqueConstraint('student_id', 'course_id', name='uq_student_course'),
        db.Index('idx_student_course', 'student_id', 'course_id'),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'student_id': self.student_id,
            'course_id': self.course_id,
            'enrollment_date': self.enrollment_date.isoformat() if self.enrollment_date else None,
            'academic_year': self.academic_year,
            'semester_term': self.semester_term,
            'exam_type': self.exam_type,
            'credit_type': self.credit_type,
            'gpa': float(self.gpa) if self.gpa else None,
            'class_number': self.class_number,
            'status': self.status,
            'score': float(self.score) if self.score else None,
            'letter_grade': self.letter_grade,
            'midterm_score': float(self.midterm_score) if self.midterm_score else None,
            'final_score': float(self.final_score) if self.final_score else None,
            'graded_at': self.graded_at.isoformat() if self.graded_at else None,
            'total_classes': self.total_classes,
            'attended': self.attended,
            'attendance_rate': float(self.attendance_rate) if self.attendance_rate else None,
        }


class AssignmentScore(db.Model):
    """作业成绩表"""
    __tablename__ = 'assignment_scores'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    student_course_id = db.Column(db.Integer, db.ForeignKey('student_courses.id'), nullable=False, index=True)
    assignment_name = db.Column(db.String(100))
    score = db.Column(db.Numeric(5, 2))
    submitted_at = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'student_course_id': self.student_course_id,
            'assignment_name': self.assignment_name,
            'score': float(self.score) if self.score else None,
            'submitted_at': self.submitted_at.isoformat() if self.submitted_at else None,
        }

